﻿using System;
using System.Data;
using System.Linq;
using System.Web.UI;
using PollSystem.Model;

namespace PollSystem
{
    public partial class _Default : Page
    {
        protected void Page_PreRender(object sender, EventArgs e)
        {
            PollSystemEntities context = new PollSystemEntities();
            using (context)
            {
                this.ListViewQuestions.DataSource = context.Questions
                                                                .Include("Answers")
                                                                .OrderBy(q => Guid.NewGuid())
                                                                .Take(3)
                                                                .ToList();
                this.DataBind();
            }
        }

        protected void LinkButtonVote_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            int answerId = Convert.ToInt32(e.CommandArgument);
            
            using(PollSystemEntities context = new PollSystemEntities())
            {
                var answer = context.Answers.Find(answerId);
                answer.Votes++;
                context.SaveChanges();
                Response.Redirect("ShowVotingResults.aspx?questionId=" + answer.QuestionId);
            }
        }
    }
}